package mysql

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"server/common/models/group"
	"server/common/models/message"
	"server/common/models/pool"
	"server/common/models/user"
	"time"
)

type Mysql struct {
	Host     string
	Port     int64
	Username string
	Password string
	Dbname   string
	Log      bool
	Object   *gorm.DB
}

func InitMysql(Host string, Port int64, Username string, Password string, Dbname string, Log bool) *Mysql {
	// 配置和mysql的连接
	connStr := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		Username, Password, Host, Port, Dbname)

	// 连接mysql
	conn, err := gorm.Open("mysql", connStr)
	if err != nil {
		fmt.Println(connStr)
		fmt.Print(err.Error())
		panic("mysql 初始异常")
	}

	// 设置连接池·
	conn.DB().SetMaxIdleConns(10)
	conn.DB().SetMaxOpenConns(100)
	conn.DB().SetConnMaxLifetime(20 * time.Second)

	// 设置日志模式
	conn.LogMode(Log)

	// 指定编码格式为utf8mb4_general_ci
	conn = conn.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci")

	return &Mysql{
		Host:     Host,
		Port:     Port,
		Username: Username,
		Password: Password,
		Dbname:   Dbname,
		Log:      Log,
		Object:   conn,
	}
}

func (m *Mysql) Migrate() {
	m.Object.AutoMigrate(
		&user.User{},
		&user.UserAuth{},
		&user.UserIntro{},
		&user.UserMatchWhere{},
		&pool.PoolUserRegister{},
		&user.UserMoment{},
		&user.UserMomentReply{},
		&message.UserMessage{},
		&message.GroupMessage{},
		&user.UserContact{},
		&group.Group{},
		&group.GroupUser{},
	)
}
